from fastapi import FastAPI, Request, Form,HTTPException
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from tool import  db as session
from model import Q_choice, Q_word
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from interf.index import router
from token_login.view import router as v_router



app = FastAPI()
app.include_router(router, prefix="/items")        # 注册分组
app.include_router(v_router, prefix="/jwt")

templates = Jinja2Templates(directory="templates")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def root(request: Request):
    choice = session.query(Q_choice).all()
    word = session.query(Q_word).all()

    return templates.TemplateResponse("index.html", {"request": request,"choice":choice,"word":word})



@app.get("/insert/")
async def say_hello(request: Request):
    return templates.TemplateResponse("insert.html", {"request": request})


@app.post("/insert_choice/")
async def insert_choice(request: Request, language: str = Form(...), question: str = Form(...), A: str = Form(...),
                        B: str = Form(...),
                        C: str = Form(...), D: str = Form(None), answer: str = Form(None)):
    print(language, question, A, B, C, D, answer)

    new_data = Q_choice(language=language, question=question, A=A, B=B, C=C, D=D, answer=answer, type=0)
    session.add(new_data)
    session.commit()
    return True


@app.post("/insert_word/")
async def insert_choice(language: str = Form(...), question: str = Form(...),
                        answer: str = Form(None)):
    print(language, question,answer)

    new_data = Q_word(language=language, question=question, answer=answer, type=1)
    session.add(new_data)
    session.commit()
    return True
from starlette.responses import JSONResponse  
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc:HTTPException):                    # 捕获异常
    return JSONResponse(  
        status_code=exc.status_code,  
        content={"message": exc.detail}
    )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run('main:app', host="0.0.0.0", port=6999, reload=True)